package com.guigu.erp.controller;

import com.guigu.erp.pojo.SysUsers;
import com.guigu.erp.service.SysUsersService;
import com.guigu.erp.utils.JwtUtils;
import com.guigu.erp.utils.PageUtils;
import com.guigu.erp.vo.SysUsersVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Author: janecraft
 * @Date: 2024/5/16
 * @Description: 后台用户表的请求控制器类
 * @Version： 1.0
 */
@CrossOrigin
@RestController
@RequestMapping("/sysusers/")
public class SysUsersController {

    @Autowired
    private SysUsersService sysUsersService;

    /**
     * 处理登录
     * @param users
     * @return
     */
    @RequestMapping("/login")
    public String login(@RequestBody SysUsers users) {
        SysUsers user = sysUsersService.getSysUserByName(users.getLoginId());
        if(user != null) {
            return JwtUtils.getJwtToken(user.getId()+"", user.getLoginId());
        }
        return null;
    }




    /**
     * 添加后台用户
     * @param users
     * @return
     */
    @PostMapping("/add")
    public String add(@RequestBody SysUsers users) {
        // 默认正常
        users.setStatus("1");
        boolean flag = sysUsersService.save(users);
        if (flag)
            return "ok";
        return "no";
    }

    @PostMapping("/upload")
    public String upload(MultipartFile photo) {
        System.out.println(photo);

        // 图片在服务器上保存的路径：
        // "d:pictures"
        File dir = new File("/Users/jane/Downloads/pictures/sysusers/");
        if(!dir.exists())
            dir.mkdir();
        // 建议建目录存放图片，目录名可以是时间，可以是类型
        String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
        // 重新命名新的图片，用uuid字符串
        String filename = UUID.randomUUID() + "_" + suffix;
        try {
            // 写文件
            photo.transferTo(new File(dir, filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        String result = "http://127.0.0.1:10001/images/sysusers/"+filename;
        System.out.println(result);
        // 返回图片路径
        return result;
    }

    /**
     * 分页查询后台用户
     * @param vo
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PostMapping("/page/{pageNo}/{pageSize}")
    public PageUtils<SysUsers> page(@RequestBody SysUsersVo vo,
                                    @PathVariable int pageNo,
                                    @PathVariable int pageSize) {
        PageUtils<SysUsers> page = this.sysUsersService.page(vo, pageNo, pageSize);
        return page;
    }





    @RequestMapping("/list")
    @ResponseBody
    public List<SysUsers> list() {
        return this.sysUsersService.list();
    }

}
